var mongoose = require('../../models/model');
var UserModel = require('../../models/user');

exports.login = function(req,res){
	console.log(req.path);
	res.render('admin/login',{title:'登录'});
};

exports.doLogin = function(req,res){
	var username = req.body.username;
	var password = req.body.password;
	var remember = req.body.remember;

	//根据用户名查找用户
	UserModel.findOne({username:username},function(err,user){
		if(err){
			console.log(err);
		}

		if(!user){
			return res.redirect('/admin/login');
		}else{
			//加密密码
			var crypto = require('crypto');
			var sha1   = crypto.createHash('sha1');
			sha1.update(password);
			password   = sha1.digest('hex');

			//匹配密码是不正确
			if(password == user.password){

				//更新登录信息到数据库
				var date             = new Date();
				user.last_login_time = date.getTime();
				user.last_login_ip   = req.ip;
				user.save();

				//记录用户信息到session
				req.session.username = user.username;
				req.session.userid = user._id.toString();

				return res.redirect('/admin');
			}else{
				return res.redirect('/admin/login');
			}
		}

	});
};

exports.logout = function(req,res){
	req.session.userid = null;
	req.session.username = null;
	return res.redirect('/admin/login');
};

exports.register = function(req,res){
	console.log(req.path);
	res.render('admin/register',{title:'注册'});
};

exports.doRegister = function(req,res){
	var username = req.body.username;
	var password = req.body.password;
	var repeat_password = req.body.repeat_password;
	var last_login_ip = register_ip = req.ip;

	//验证确认密码
	if(password != repeat_password){
		//res.flush({status:0,msg:'确认密码不一致',data:null});
		return res.redirect('/admin/register');
	}

	//判断用户名是不已经被注册
	UserModel.findOne({username:username},function(err,user){
		if(err){
			console.log(err);
		}

		if(user){
			return res.redirect('/admin/register');
		}else{
			
			//加密密码
			var crypto = require('crypto');
			var sha1   = crypto.createHash('sha1');
			sha1.update(password);
			password   = sha1.digest('hex');

			//存入数据库
			var UserEntity = new UserModel({username:username,password:password,register_ip:register_ip});
			UserEntity.save(function(err){
				if(err){
					console.log(err);
				}

				return res.redirect('/admin/login');
			});
		}
	});

};